package com.imoblife.brainwavestus.customview;

import java.util.Timer;
import java.util.TimerTask;

import com.imoblife.brainwavestus.R;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItem;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItemPragrame;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItem.DownLoadingListener;
import com.imoblife.brainwavestus.oldMedia.MusicMediaPlayer;
import com.imoblife.brainwavestus.service.DownLoadSchedulerSystem;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class DisplayPrewWindows {

	boolean isDownLoading = false;
	Dialog windows;
	ProgressBar downloadProgress;
	SeekBar playSeekBar;
	TextView titleView;
	Button close;
	Button replay;
	String taskName;
	String title;
	CheckBox playCheckBox;
	MusicMediaPlayer musicMediaPlayer;
	private Activity activity;
	DownLoadingListener downLoadingListener;

	public DisplayPrewWindows(CheckBox checkBox, Activity in, String taskName,
			String title) {
		downLoadingListener = DownLoadItem.getDownLoadingListener();
		this.title = title;
		this.activity = in;
		this.playCheckBox = checkBox;
		windows = new Dialog(in, android.R.style.Theme_Panel) {

			protected void onStop() {

				windows.cancel();
				super.onStop();
			}

			public void onWindowFocusChanged(boolean hasFocus) {

				if (!hasFocus) {
					windows.cancel();
				}
				super.onWindowFocusChanged(hasFocus);
			}

		};
		windows.setContentView(R.layout.prew_layout);
		windows.show();

		downloadProgress = (ProgressBar) windows
				.findViewById(R.id.downlaod_progress);

		playSeekBar = (SeekBar) windows.findViewById(R.id.play_progress);

		titleView = (TextView) windows.findViewById(R.id.downlaod_info);

		close = (Button) windows.findViewById(R.id.close);

		replay = (Button) windows.findViewById(R.id.restart);

		String downloadTaskName = taskName + ".prew";
		this.taskName = downloadTaskName;
		setActione();
	}

	private void initDownLoadState() {
		((View) playSeekBar.getParent()).setVisibility(View.GONE);
		downloadProgress.setVisibility(View.VISIBLE);

		Intent intent = new Intent(
				DownLoadSchedulerSystem.ACT_SCHEDULER_DOWNLAOD);

		intent.putExtra("command",
				DownLoadSchedulerSystem.COMMAND_RECAIVER_PREW_START);
		intent.putExtra(DownLoadSchedulerSystem.COMMAND_RECAIVER_PREW_START,
				taskName);

		activity.sendBroadcast(intent);

		replay.setEnabled(false);

		DownLoadItem.setDownLoadingListener(new DownLoadingListener() {

			int count = 0;
			String tag = taskName.replace(" ", "+");

			public void downloading(String downlaodname, int extr,
					final long progress, final long size) {

				if (extr == DownLoadItemPragrame.EXTR_SUCC) {

					if (downlaodname.equals(tag)) {
						if (progress != size) {

							if (count % 10 == 0) {
								downloadProgress.post(new Runnable() {

									public void run() {
										downloadProgress.setMax((int) size);
										downloadProgress
												.setProgress((int) progress + 10);
									}
								});
							}
							count++;
						} else {
							downloadProgress.postDelayed(new Runnable() {
								public void run() {
									replay.setEnabled(true);
									((View) playSeekBar.getParent())
											.setVisibility(View.VISIBLE);
									downloadProgress.setVisibility(View.GONE);
									titleView.setText(title);
									musicMediaPlayer = new MusicMediaPlayer(
											taskName);
									musicMediaPlayer.decryptPlay(activity);
									updateMusicPlayProgress();
								}
							}, 1000);
							// activity.registerDownLoadingListener();
						}
					}
				}

				if (extr == DownLoadItemPragrame.EXTR_FAILE_NET) {
					titleView.post(new Runnable() {
						public void run() {
							titleView.setText(R.string.error_net);
						}
					});

				} else if (extr == DownLoadItemPragrame.EXTR_FAILE_SDCARDE) {

					titleView.post(new Runnable() {
						public void run() {
							titleView.setText(R.string.error_sdcard);
						}
					});
				}

			}
		});

	}

	private void setActione() {

		if (DownLoadSchedulerSystem.getDownloadTaskState(taskName, activity) != DownLoadItemPragrame.DOWN_STATE_END) {
			initDownLoadState();
		} else {
			musicMediaPlayer = new MusicMediaPlayer(taskName);
			if (musicMediaPlayer.decryptPlay(activity)) {
				replay.setEnabled(true);
				((View) playSeekBar.getParent()).setVisibility(View.VISIBLE);
				downloadProgress.setVisibility(View.GONE);
				titleView.setText(title);
				updateMusicPlayProgress();
			} else {
				initDownLoadState();
			}
		}

		windows.setOnCancelListener(new OnCancelListener() {

			public void onCancel(DialogInterface dialog) {

				if (replay.isEnabled()) {

					musicMediaPlayer.encryptStop(activity);
				}

				playCheckBox.setChecked(false);
				if (timer != null) {
					timer.cancel();
					isPlay = false;
				}

			}
		});
		close.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				windows.cancel();

			}
		});

	}

	Timer timer;
	TextView left;
	TextView right;
	long current = 0;
	boolean isPlay = true;

	private void updateMusicPlayProgress() {
		musicMediaPlayer.getMediaPlayer().setOnCompletionListener(
				new OnCompletionListener() {

					public void onCompletion(MediaPlayer mp) {
						isPlay = false;
						right.setText("--:--");
					}
				});

		replay.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				current = 0;

				musicMediaPlayer = new MusicMediaPlayer(taskName);
				musicMediaPlayer.decryptPlay(activity);
				musicMediaPlayer.getMediaPlayer().setLooping(false);
				isPlay = true;
				left.setText(gettime(current));
				downloadProgress.setProgress(0);

			}
		});

		left = (TextView) windows.findViewById(R.id.left);
		right = (TextView) windows.findViewById(R.id.right);
		timer = new Timer("update", false);
		timer.schedule(new TimerTask() {

			public void run() {
				if (isPlay) {
					current += 1000;
					if (current >= musicMediaPlayer.getMediaPlayer()
							.getDuration()) {
						current = musicMediaPlayer.getMediaPlayer()
								.getDuration();
						isPlay = false;
					}

					playSeekBar.post(new Runnable() {

						public void run() {
							playSeekBar.setProgress((int) current);
						}
					});
				}
			}
		}, 1, 1000);

		playSeekBar.setMax(musicMediaPlayer.getMediaPlayer().getDuration());
		playSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			public void onStopTrackingTouch(SeekBar seekBar) {

			}

			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if (fromUser) {
					musicMediaPlayer.getMediaPlayer().seekTo(progress);
					current = progress;
				}
				left.setText(gettime(current));
				right.setText("-"
						+ gettime(musicMediaPlayer.getMediaPlayer()
								.getDuration() - current));
			}
		});

	}

	public String gettime(long durctions) {
		long mintue = durctions / 1000 / 60;
		long second = (durctions - mintue * 60000) / 1000;
		String mm = null, ss = null;
		if (mintue < 10) {
			mm = "0" + mintue;
		} else {
			mm = mintue + "";
		}
		if (second < 10) {
			ss = "0" + second;
		} else {
			ss = second + "";
		}
		return mm + ":" + ss;
	}
}
